import './css/index.css';
import ajaxFn from './js/ajax.js';
const baseUrl = 'https://service-dmsf9bxc-1251395798.gz.apigw.tencentcs.com';

//   GET请求
ajaxFn({
  baseUrl,
  url: '/release/api/web/carouselGroup/getAllCarouselGroup',
  method: 'GET',
  data: {
    projectId: 6,
  },
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
  callBack: (res) => {
    console.log(res);

    let currentIndex = 0;
    let imgArr = res.data.rows[0].w_carousels;
    let box1 = document.querySelector('.box-1');
    console.log(imgArr);
    imgArr.forEach(() => {
      box1.innerHTML += '<div class="circle"></div>';
    });

    const box = document.querySelector('.box');
    const circles = document.querySelectorAll('.circle');
    let autoPlayInterval;

    function updatePhoto() {
      box.classList.add('transition');
      setTimeout(() => {
        box.style.backgroundImage = `url(${imgArr[currentIndex].url})`;
      }, 300);

      circles.forEach((circle, index) => {
        circle.classList.toggle('active', index === currentIndex);
      });
    }

    circles.forEach((circle, index) => {
      circle.addEventListener('click', () => {
        currentIndex = index;
        updatePhoto();
        autoPlay();
      });
    });

    document.querySelector('.left').addEventListener('click', () => {
      currentIndex = (currentIndex - 1 + imgArr.length) % imgArr.length;
      updatePhoto();
      autoPlay();
    });

    document.querySelector('.right').addEventListener('click', () => {
      currentIndex = (currentIndex + 1) % imgArr.length;
      updatePhoto();
      autoPlay();
    });

    function autoPlay() {
      clearInterval(autoPlayInterval);
      autoPlayInterval = setInterval(() => {
        currentIndex = (currentIndex + 1) % imgArr.length;
        updatePhoto();
      }, 3000);
    }

    updatePhoto();
    autoPlay();
  },
});
